﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using nanoCMS.Blog.Concrete;
using nanoCMS.Core;
using nanoCMS.Core.Helpers;

namespace nanoCMS.Blog.Providers {
	public class BlogCategoryProvider {
		//TODO: Add setting to limit if blog post could be in multiple tenants

		private readonly WorldContext worldContext;
		private BlogEntities _entities; //DO NOT ACCESS DIRECTLY
		private BlogEntities Entities {
			get { return _entities ?? (_entities = new BlogEntities(worldContext.EntityConnectionString)); }
		}

		public BlogCategoryProvider(WorldContext worldContext) {
			this.worldContext = worldContext;
		}


		private bool IsUrlInUse(string url, int tenantID, int excludeBlogCategoryID = 0) {
			return Entities.BlogCategories.Any(x => x.Url == url && x.TenantID == tenantID);
		}


		public BlogReturn Add(string title, string description, out BlogCategory blogCategory, int tenantID = 1) {
			string encodedUrl = UrlHelper.StringToUrl(title);
			string tempUrl;
			for (int i = 0; ; i++) {
				tempUrl = encodedUrl;
				if (i != 0) tempUrl += i;

				if (!IsUrlInUse(tempUrl, tenantID)) break;
			}

			blogCategory = new BlogCategory {
				Title = title,
				Url = tempUrl,
				Description = description,
				TenantID = tenantID
			};

			Entities.BlogCategories.AddObject(blogCategory);
			Entities.SaveChanges();
			return BlogReturn.Success;
		}

		public List<BlogCategory> GetCategoriesForTenant(int tenantId = 1) {
			return Entities.BlogCategories.Where(x => x.TenantID == tenantId).ToList();
		}

		public bool AddBlogPostToCategory(int blogPostID, int categoryID) {
			var blogPost = Entities.BlogPosts.SingleOrDefault(x => x.BlogPostID == blogPostID);
			if (blogPost == null) throw new ArgumentException("There isn't BlogPost with ID=" + blogPostID);
			if (blogPost.BlogCategories != null && !blogPost.BlogCategories.Any(x => x.BlogCategoryID == categoryID))
				return AddBlogPostToCategory(blogPost, categoryID);
			return false;
		}

		private bool AddBlogPostToCategory(BlogPost blogPost, int categoryID) {
			var category = Entities.BlogCategories.SingleOrDefault(x => x.BlogCategoryID == categoryID);
			if (category == null) throw new ArgumentException("There isn't BlogCategory with ID=" + categoryID);
			blogPost.BlogCategories.Add(category);
			Entities.SaveChanges();
			return true;
		}


		public bool EditBlogPostInCategories(int blogPost, int categoryID)
		{

			return true;
		}

		public bool Edit(int blogCategoryID, string title, string description)
		{
			BlogCategory blogCategory = Get(blogCategoryID);
			if (blogCategory == null) return false;
			blogCategory.Title = title;
			blogCategory.Description = description;
			Entities.SaveChanges();
			return true;
		}

		public BlogCategory Get(int blogCategoryID)
		{
			return Entities.BlogCategories.SingleOrDefault(x => x.BlogCategoryID == blogCategoryID);
		}
	}
}
